//
//  WaterWaveView.m
//  WaterWaveTest
//
//  Created by 雷传营 on 16/5/14.
//  Copyright © 2016年 BrotherCompany. All rights reserved.
//

#import "WaterWaveView.h"

@interface WaterWaveView ()
{
    UIColor * waterColor;
    float     offSetOfSin;
    float     coordinateY;
}
@end

@implementation WaterWaveView

-(id)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor clearColor];
        offSetOfSin = 0; //X轴坐标偏移量
        coordinateY = 50; //Y轴坐标的基准点（波浪的中间线）
        waterColor = [UIColor blueColor];//波浪的填充色
        [NSTimer scheduledTimerWithTimeInterval:0.02 target:self selector:@selector(animateion) userInfo:nil repeats:YES];//通过定时器，不断偏移x轴坐标，重绘图像，实现效果
    }
    return self;
}

-(void)animateion{

    offSetOfSin += 0.1;
    [self setNeedsDisplay];
    
}

-(void)drawRect:(CGRect)rect{
    
    CGContextRef  context = UIGraphicsGetCurrentContext();//获取上下文，所谓的上下文，读者可以理解成一个用来画画的画板。
    CGMutablePathRef path = CGPathCreateMutable();//创建一条绘图的路径
    CGContextSetLineWidth(context, 1);//设置线的宽度
    CGContextSetFillColorWithColor(context, [waterColor CGColor]);//设置填充色
    
    CGPathMoveToPoint(path, nil, 0, coordinateY);//设置起点
    //添加一大堆绘制的点（绘制波浪线需要的点）
    for (int x = 0; x<=100; x++) {
        float  y = sin(x /180*M_PI + 4*offSetOfSin/M_PI) * 5 + coordinateY;
        CGPathAddLineToPoint(path, nil, x, y);
    }
    CGPathAddLineToPoint(path, nil, rect.size.width, rect.size.height); //这个点，确定了绘制的方向，即向下绘制
    CGPathAddLineToPoint(path, nil, 0, rect.size.height);//这个点确保下方类似于一个矩形
    
    // 注意：绘制的时候按照点的先后顺序绘制线
    CGContextAddPath(context, path);//把绘制直线的绘图信息保存到图形上下文中
    CGContextFillPath(context);//填充绘制区域
    CGContextDrawPath(context, kCGPathStroke);//填充规则
    CGPathRelease(path);//但凡通过quarzt2d中带有creat/copy/retain方法创建出来的值都必须手动的释放
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
